//
//  ExamCollectionQuestionViewController.m
//  JPWords
//
//  Created by 梁淑婷 on 2024/7/16.
//

#import "ExamCollectionQuestionViewController.h"
#import "ExamQuestionsCollectionViewCell.h"
#import "ExamCollectQuestionManager.h"
#import "ExamQuestionWriteCollectionViewCell.h"

@interface ExamCollectionQuestionViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,JPAPIManagerCallBackDelegate,ExamQuestionsCollectionViewCellDelegate>

@property(nonatomic,strong)ExamCollectQuestionManager *questionManager;
@property(nonatomic,strong)AVPlayer *avPlayer;
@property(nonatomic,assign)BOOL isPlaying;
@property(nonatomic,strong)ExamQuestionsCollectionViewCell *currentHearingCell;//当前播放音频的cell
@property(nonatomic,copy)NSString *currentHearingFile;//当前听力文件
@property(nonatomic,strong)JPProgressHUD *loadingHub;
@property(nonatomic,assign)NSInteger sel_index;

@end

@implementation ExamCollectionQuestionViewController

-(NSMutableArray *)dataArr{
    if(!_dataArr){
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}

-(ExamCollectQuestionManager *)questionManager{
    if(!_questionManager){
        _questionManager = [[ExamCollectQuestionManager alloc]init];
        _questionManager.delegate = self;
    }
    return _questionManager;
}

-(void)viewDidLoad{
    [super viewDidLoad];
    [self createUI];
    self.isPlaying = NO;
    //听力播放结束
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(playToEndTime:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
}

-(void)setTypeModel:(ExamPaperTypeListModel *)typeModel{
    _typeModel = typeModel;
    self.loadingHub = [JPProgressHUD showLoadingInView:self.view];
    [self loadQuestionData];
}

-(void)refreshData{
    [self.collectionView reloadData];
    [self.collectionView setContentOffset:CGPointMake(0,0) animated:NO];
}

#pragma mark - 暂停听力播放
-(void)stopHearingPlay{
    if(self.avPlayer){
        self.isPlaying = NO;
        [self.avPlayer pause];
        if(self.currentHearingCell){
            [self.currentHearingCell stopVoiceAnimation];
        }
    }
}

#pragma mark - 获取专项测试数据
-(void)loadQuestionData{
    self.questionManager.grade = self.grade;
    self.questionManager.type = self.typeModel.typeId;
    [self.questionManager loadData];
}

-(void)createUI{
    
    self.customNavigationBar.hidden = YES;
    self.view.backgroundColor = UIColorHex(0xF2F7F6);
    
    [self createCollecionView];
    
}

#pragma mark - 创建collectionview
-(void)createCollecionView{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    [layout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0,0, self.currentAvailableWidth,self.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT-42) collectionViewLayout:layout];
    self.collectionView.showsHorizontalScrollIndicator = NO;
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.scrollEnabled = YES;
    self.collectionView.pagingEnabled = YES;
    self.collectionView.backgroundColor = UIColorHex(0xF2F7F6);
    [self.collectionView registerClass:NSClassFromString(@"ExamQuestionsCollectionViewCell") forCellWithReuseIdentifier:@"ExamQuestionsCollectionViewCell"];
    [self.collectionView registerClass:NSClassFromString(@"ExamQuestionWriteCollectionViewCell") forCellWithReuseIdentifier:@"ExamQuestionWriteCollectionViewCell"];
    [self.view addSubview:self.collectionView];
}

-(void)refreshWidth{
    // 获取当前可用宽度并更新布局
    self.currentAvailableWidth = [DeviceUtils currentAvailableWidth];
    self.currentAvailableHeight = [DeviceUtils currentAvailableHeight];
    self.customNavigationBar.frame = CGRectMake(0, 0, self.currentAvailableWidth,kYM_NAVIGATIONBAR_HEIGHT);
    NSInteger index = self.sel_index;
    [self.collectionView removeFromSuperview];
    [self createCollecionView];
    [self.collectionView reloadData];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
         [self.collectionView setContentOffset:CGPointMake(index*self.currentAvailableWidth,0) animated:NO];
    });
}


#pragma mark collectionView代理方法
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.dataArr.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    ExamQuestionModel *model = self.dataArr[indexPath.item];
    if([model.type isEqualToString:@"36"]){
        //写作
        ExamQuestionWriteCollectionViewCell *cell= [collectionView dequeueReusableCellWithReuseIdentifier:@"ExamQuestionWriteCollectionViewCell" forIndexPath:indexPath];
        cell.row = indexPath.item;
        cell.testType = 4;
        cell.model = model;
        return cell;
        
    }
    
    ExamQuestionsCollectionViewCell *cell= [collectionView dequeueReusableCellWithReuseIdentifier:@"ExamQuestionsCollectionViewCell" forIndexPath:indexPath];
    cell.item = indexPath.item;
    cell.testType = 4;
    cell.model = model;
    cell.delegate = self;
    [cell refeshUI];
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(self.currentAvailableWidth,self.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT-38);
}


- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
     return UIEdgeInsetsMake(-15,0,0,0);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
     return 0;
}


- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
     return 0;
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if([scrollView isEqual:self.collectionView]){
        NSInteger c_index = scrollView.contentOffset.x/self.currentAvailableWidth;
        self.sel_index = c_index;
        if(c_index < self.dataArr.count){
            ExamQuestionModel *model = self.dataArr[c_index];
            if(model.type.integerValue == 33&&self.isPlaying == YES){
                if(self.avPlayer){
                    [self.avPlayer pause];
                    if(self.currentHearingCell){
                        [self.currentHearingCell stopVoiceAnimation];
                    }
                }
            }
            if (self.delegate && [self.delegate respondsToSelector:@selector(pageScroll:andOptionsModel:andIndex:)]){
                [self.delegate pageScroll:self andOptionsModel:model andIndex:c_index];
            }
        }
    }
}


#pragma mark - 听力点击
-(void)hearingTap:(ExamQuestionsCollectionViewCell *)cell{
    if(cell.model.hearingFile&&![cell.model.hearingFile isEqualToString:@""]){
        self.currentHearingCell = cell;
        if([self.currentHearingFile isEqualToString:cell.model.hearingFile]){
            //还是当前的题目
            if(self.avPlayer){
                if (self.isPlaying == YES){
                    [self.avPlayer pause];
                    if(self.currentHearingCell){
                        [self.currentHearingCell stopVoiceAnimation];
                    }
                } else {
                    if (CMTimeCompare(self.avPlayer.currentItem.currentTime, self.avPlayer.currentItem.duration) == 0) {
                        [self.avPlayer seekToTime:kCMTimeZero];
                    }
                    [self.avPlayer play];
                    if(self.currentHearingCell){
                        [self.currentHearingCell startVoiceAnimation];
                    }
                }
                self.isPlaying = !self.isPlaying;
            }else{
                [self playListenWithHearingFile:cell.model.hearingFile];
            }
        }else{
            //重新播放新的
            [self playListenWithHearingFile:cell.model.hearingFile];
        }
    }else{
        [JPProgressHUD showMsg:@"听力文件不存在"];
    }
}

#pragma mark - 听力播放
-(void)playListenWithHearingFile:(NSString*)hearingFile{
    if(hearingFile&&![hearingFile isEqualToString:@""]){
        self.currentHearingFile = hearingFile;
        AVPlayerItem *item = [[AVPlayerItem alloc] initWithURL:[NSURL URLWithString:hearingFile]];
        [item addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
        if(self.avPlayer){
            [self.avPlayer pause];
            [self.avPlayer replaceCurrentItemWithPlayerItem:item];
        }else{
            self.avPlayer = [[AVPlayer alloc] initWithPlayerItem:item];
        }
        [self.avPlayer play];
        self.isPlaying = YES;
    }else{
        [JPProgressHUD showMsg:@"听力文件不存在"];
    }
}


-(void)playToEndTime:(NSNotification*)notifi{
    if(self.currentHearingCell){
        [self.currentHearingCell stopVoiceAnimation];
    }
    [self.avPlayer seekToTime:kCMTimeZero];
    self.isPlaying = NO;
}


-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if ([keyPath isEqualToString:@"status"]) {
        AVPlayerItemStatus status = [change[NSKeyValueChangeNewKey] integerValue];
        if (status == AVPlayerItemStatusReadyToPlay) {
            NSLog(@"播放成功");
            if(self.currentHearingCell){
                [self.currentHearingCell startVoiceAnimation];
            }
        } else if (status == AVPlayerItemStatusFailed) {
            NSLog(@"播放失败");
            self.isPlaying = NO;
            [JPProgressHUD showMsg:@"听力播放失败"];
            if(self.currentHearingCell){
                [self.currentHearingCell stopVoiceAnimation];
            }
        }
    }
}


#pragma mark - JPAPIManagerCallBackDelegate
-(void)managerCallDLDLAPIDidSuccess:(JPAPIBaseManager *)manager{
    
    if([manager isEqual:self.questionManager]){
        if(self.loadingHub){
            [self.loadingHub removeFromSuperview];
        }
        NSDictionary *dic = manager.response.content;
        NSArray *arr = [ExamQuestionModel mj_objectArrayWithKeyValuesArray:dic[@"data"]];
        for(NSInteger i = 0;i < arr.count;i++){
            ExamQuestionModel *model = arr[i];
            NSArray *questionOptions = [ExamQuestionOptionsModel mj_objectArrayWithKeyValuesArray:model.questionOptions];
            model.questionOptions = questionOptions;
            [self.dataArr addObject:model];
        }
        if(self.index == 0){
            if(self.dataArr.count > 0){
                if (self.delegate && [self.delegate respondsToSelector:@selector(firstRefresh:andModel:)]){
                    [self.delegate firstRefresh:self andModel:self.dataArr[0]];
                }
            }
        }
        [self.collectionView reloadData];
    }
    
}


-(void)managerCallDLDLAPIDidFailed:(JPAPIBaseManager *)manager{
    if([manager isEqual:self.questionManager]){
        if(self.loadingHub){
            [self.loadingHub removeFromSuperview];
        }
    }
    if(manager.errorMessage){
        [JPProgressHUD showMsg:manager.errorMessage];
    }
    
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    if(self.avPlayer){
        [self.avPlayer pause];
        self.avPlayer = nil;
    }
}

@end
